package com.Jiang.dao;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DateBase {
    //工具人类
    private static DataSource ds = null;
    static{
        try{
//读取db.properties文件中的数据库连接信息
            InputStream in = com.Jiang.dao.DateBase.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties prop = new Properties();
            prop.load(in);
            ds= BasicDataSourceFactory.createDataSource(prop);
        }catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    // 获取数据库连接对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //释放资源
    public static void release(Connection conn,PreparedStatement st,ResultSet rs){
        if(rs!=null){
            try{
//关闭存储查询结果的ResultSet对象
                rs.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(st!=null){
            try{
//关闭负责执行SQL命令的Statement对象
                st.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try{
//将Connection连接对象还给数据库连接池
                conn.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //查
    public static ResultSet FindDateBase(Connection connection,String sql,Object []a) throws SQLException {
        PreparedStatement st=connection.prepareStatement(sql);
        for (int i = 0; i < a.length; i++) {
            st.setObject(i+1,a[i]);
        }
        return st.executeQuery();
    }
    //更新数据
    public static int UpdateDateBase(Connection connection,String sql,Object []a) throws SQLException {
        PreparedStatement st=connection.prepareStatement(sql);
        for (int i = 0; i < a.length; i++) {
            st.setObject(i+1,a[i]);
        }
        return st.executeUpdate();
    }

    public static void closeResource(Connection connection){
        if(connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
